require(['./config'],()=>{
    require(['template','url', 'header','utils','footer','fly'],(template,url,header)=>{
        class Index {
            constructor(){
                this.list().then(()=>{
                    this.render()
                    this.addToCart()
                    this.box = document.querySelector('#box')
                    this.bigBox = document.querySelector('#bigBox')
                    this.span = document.querySelector('#box span')
                    this.bigImg = document.querySelector('#bigBox img')
                    this.bindEvents()
                })
            }
            list(){
                const id=window.location.search.slice(1).split('&').reduce((obj,item)=>{
                    var arr=item.split('=')
                    obj[arr[0]]=arr[1]
                    return obj
                },{}).id
                //再别的方法可能还会使用
                this.id=Number(id)
                return new Promise(resolve=>{
                    $.get(`${url.rap2}/api/xiangqing`,{id:this.id},resp=>{
                       if(resp.code===200){
                           const{detail}=resp.body
                           this.detail={...detail,id:this.id}
                           resolve()
                       }
                    })
                })
            }
            render(){
                $('#shopping').html(template('detailTmplate',{
                   ...this.detail
                }))
            }
            addToCart(){
                $('#okBnt').on('click',(e)=>{
                    this.fly(e)
                    let cart=localStorage.getItem('cart')
                    if(cart){
                        cart=JSON.parse(cart)
                        const isExist=cart.some(shop=>{
                            return shop.id===this.detail.id
                        })
                        if(isExist){
                            cart=cart.map(shop=>{
                                if(shop.id===this.detail.id){
                                    shop.count++
                                }
                                return shop
                            })
                        }else{
                            cart.push({
                                ...this.detail,
                                count:1,
                                checked:true
                            })
                        }

                        // cart=JSON.parse(cart)
                        // cart.push(this.detail)
                        localStorage.setItem('cart',JSON.stringify(cart))

                    }else{
                        // this.detail.count=1
                        // var arr=[this.detail]
                        // localStorage.setItem('cart',JSON.stringify(arr))
                        localStorage.setItem('cart',JSON.stringify([{
                            ...this.detail,
                            count:1,
                            checked:true
                        }]))

                    }
                })

            }
            fly(e){
                //加入购物车得抛物线
                $(`<img src="${this.detail.img[0]}" style="width: 50px;height: 50px;border-radius:50%">`).fly({
                    start:{
                      left: e.clientX,  //开始位置（必填）#fly元素会被设置成position: fixed
                      top: e.clientY,  //开始位置（必填）
                    },
                    end:{
                      left: $('#cart').offset().left - $(window).scrollLeft(), //结束位置（必填）
                      top: $('#cart').offset().top - $(window).scrollTop() //结束位置（必填）
                    },
                    speed: 1.1, //越大越快，默认1.2
                    vertex_Rtop: 100, //运动轨迹最高点top值，默认20
                    onEnd: function () {
                        this.destroy()
                        // 调用header里封装好的方法重新计算数量
                        header.calcCartTotal()
                    }
                  }) 
                }
                bindEvents () {
                    this.box.onmouseenter = () => {
                        this.toggleDisplay('block')
                    }
                    this.box.onmouseleave = () => {
                        this.toggleDisplay('none')
                    }
                    this.box.onmousemove = e => {
                        // 鼠标到文档顶部坐标减去盒子到文档顶部坐标得到的就是鼠标到盒子顶部的距离
                        var top = e.pageY - utils.getOffset(this.box).top
                        var left = e.pageX - utils.getOffset(this.box).left
                        // span的坐标应该是鼠标到盒子顶部距离减去宽高的一半
                        left -= this.span.offsetWidth / 2
                        top -= this.span.offsetHeight / 2
                        this.move(left, top)
                    }
                }
                toggleDisplay (display) {
                    this.span.style.display = display
                    this.bigBox.style.display = display
                }
                move (left, top) {
                    // 限定范围
                    if (left < 0) left = 0
                    if (top < 0) top = 0
                    if (left > this.box.offsetWidth - this.span.offsetWidth)
                        left = this.box.offsetWidth - this.span.offsetWidth
                    if (top > this.box.offsetHeight - this.span.offsetHeight)
                        top = this.box.offsetHeight - this.span.offsetHeight
                    
                    this.span.style.left = left + 'px'
                    this.span.style.top = top + 'px'
                    // 大图坐标是span坐标的-2倍
                    this.bigImg.style.left = -2 * left + 'px'
                    this.bigImg.style.top = -2 * top + 'px'
                    
                }
        }
        new Index()      
    })
})
